package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.nursing.service.IHealthAssessmentService;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 入住Service业务层处理
 *
 * @author elina
 * @date 2025-09-30
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private IHealthAssessmentService healthAssessmentService;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckInDetailVo selectCheckInById(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        CheckIn checkIn = checkInMapper.selectById(id);
        if (ObjectUtils.isEmpty(checkIn))
            throw new BaseException("入住信息异常！");
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        if (ObjectUtils.isEmpty(elder))
            throw new BaseException("该老人不存在！");
        BeanUtil.copyProperties(elder, checkInElderVo);
        checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtil.copyProperties(checkIn, checkInConfigVo);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>().eq(CheckInConfig::getCheckInId, id));
        if (ObjectUtils.isEmpty(checkInConfig))
            throw new BaseException("入住配置异常！");
        BeanUtil.copyProperties(checkInConfig, checkInConfigVo);
        Object parse = JSON.parse(checkIn.getRemark());
        if (ObjectUtils.isNotEmpty(parse))
            checkInDetailVo.setElderFamilyVoList((List<ElderFamilyVo>) parse);

        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getElderId, elder.getId()));
        if (ObjectUtils.isEmpty(contract))
            throw new BaseException("签约办理异常！");
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }

    /**
     * 申请入住
     *
     * @param checkInApplyDto
     * @return
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        // 1. 检验老人是否已入住
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        // 通过身份证号查询老人
        LambdaQueryWrapper<Elder> elq = new LambdaQueryWrapper<Elder>().eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo())
                .eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(elq);
        // 已入住直接退出
        if (ObjectUtils.isNotEmpty(elder))
            throw new RuntimeException("老人已入住！");
        // 没有入住继续执行流程
        // 2. 更新床位状态为已入住
        Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        // 3. 新增或更新老人
        elder = insertOrUpdate(checkInElderDto, bed);
        // 4. 新增签约办理
        insertContract(checkInApplyDto, elder);
        // 5. 新增入住信息
        CheckIn checkIn = insertCheckIn(checkInApplyDto, elder, bed);
        // 6. 新增入住配置
        insertCheckInConfig(checkInApplyDto, checkIn);
        // 7. 修改健康评估表的状态为已入住
        HealthAssessment healthAssessment = healthAssessmentService.lambdaQuery().eq(HealthAssessment::getIdCard, checkIn.getIdCardNo()).one();
        if (ObjectUtil.isEmpty(healthAssessment)) {
            throw new BaseException("老人健康评估信息异常！");
        }
        healthAssessment.setAdmissionStatus(0);
        healthAssessmentService.updateById(healthAssessment);
    }

    private void insertCheckInConfig(CheckInApplyDto checkInApplyDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtil.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn insertCheckIn(CheckInApplyDto checkInApplyDto, Elder elder, Bed bed) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    private void insertContract(CheckInApplyDto checkInApplyDto, Elder elder) {
        Contract contract = new Contract();
        BeanUtil.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        // 签约时间小于当前时间，生效
        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = checkInApplyDto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        if (startDate.isBefore(LocalDateTime.now()))
            contract.setStatus(1);
        // 获取合同编号
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        // 插入数据库
        contractMapper.insert(contract);
    }


    private Elder insertOrUpdate(CheckInElderDto checkInElderDto, Bed bed) {
        Elder elder = new Elder();
        BeanUtil.copyProperties(checkInElderDto, elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);

        Elder elderDB = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo()));

        if (ObjectUtils.isNotEmpty(elderDB)) {
            // 更新
            elderMapper.updateById(elder);
        }
        // 新增
        elderMapper.insert(elder);
        return elder;
    }
}
